package com.better.frontend.controller.report;

import com.better.ZxycalApplication;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by Administrator on 2018/1/30.
 * 创建考试相关模板文件下载
 */
@Api(value = "下载模板文件管理", tags = "下载模板文件管理")
@RestController
@RequestMapping("api/download")
public class TemplateFileDownController {
    private Logger logger = LoggerFactory.getLogger(ZxycalApplication.class);

    @ApiOperation(value = "下载考试模板文件", notes = "下载考试模板文件")
    @RequestMapping(value = "/tempFile", method = {RequestMethod.POST, RequestMethod.GET})
    public ResponseEntity FileDownload(HttpServletResponse resp) throws IOException {
        try {
            Resource resource = new ClassPathResource("static/js/echarts.min.js");
            File file = resource.getFile();
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            //headers.add("Content-Disposition", String.format("attachment; filename=\"%s", URLEncoder.encode(file.getName(), "utf-8")));
            headers.add("Content-Disposition", "attachment; filename="+URLEncoder.encode(file.getName(), "utf-8"));
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            headers.add("charset", "utf-8");
            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .contentType(MediaType.parseMediaType(getContentType(file.getName())))
                    .body(resource);
        } catch (Exception e) {
            HttpHeaders falseHeaders = new HttpHeaders();
            falseHeaders.add("Pragma", "no-cache");
            falseHeaders.add("Expires", "0");
            falseHeaders.add("Cache-Control", "no-cache, no-store, must-revalidate");
            falseHeaders.add("Content-Disposition", "inline;filename=\"" + "404.jpg" + "\"");
           /* FileSystemResource falseFile = new FileSystemResource(new ClassPathResource("static/img/404.png").getFile());*/
            Resource falseFile = new ClassPathResource("static/img/404.png");
            return ResponseEntity
                    .ok()
                    .headers(falseHeaders)
                    .contentLength(falseFile.contentLength())
                    .contentType(MediaType.parseMediaType("image/jpeg"))
                    .body(falseFile);
        }
    }


    /**
     * 根据文件类型组装ContentType
     *
     * @param fileName 文件名
     * @return
     */

    private String getContentType(String fileName) {
        logger.debug("getContentType入参fileName：{}", fileName);
        if (StringUtils.isEmpty(fileName) || StringUtils.isEmpty(getExtName(fileName))) {
            return "文件名[" + fileName + "]不规范";
        }
        String fileType = getExtName(fileName);
        if (fileType.equalsIgnoreCase("xls")) {
            return "application/vnd.ms-excel";
        } else if (fileType.equalsIgnoreCase("xlsx")) {
            return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        } else if (fileType.equalsIgnoreCase("doc")) {
            return "application/msword";
        } else if (fileType.equalsIgnoreCase("docx")) {
            return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        } else if (fileType.equalsIgnoreCase("txt")) {
            return "text/plain";
        } else if (fileType.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        } else if (fileType.equalsIgnoreCase("pptx")) {
            return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
        } else if (fileType.equalsIgnoreCase("pdf")) {
            return "application/pdf";
        } else if (fileType.equalsIgnoreCase("jpg")) {
            return "image/jpeg";
        } else if (fileType.equalsIgnoreCase("png")) {
            return "image/png";
        } else if (fileType.equalsIgnoreCase("mp3")) {
            return "video/mp4";
        } else if (fileType.equalsIgnoreCase("mp4")) {
            return "video/mp4";
        } else if(fileType.equalsIgnoreCase("zip")){
            return "application/zip";
        }else {
            //return "application/force-download";// 设置强制下载不打开
            return "application/octet-stream";
        }
    }

    private String getExtName(String fileName) {
        logger.debug("getExtName入参fileName：{}", fileName);
        int i = fileName.lastIndexOf(".");
        int length = fileName.length();
        return (i > 0 ? (i + 1) == length ? "" : fileName.substring(i + 1, length) : "");
    }

}
